﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jenvin.Library.Cache
{
    /// <summary>
    /// 利用不可变特性的。读的时候不要加锁，在写的要加锁并重新复制原来的数据。写的性能不如读写锁
    /// 在写特别少。读很多的情况下使用。比如分类 。
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class FreeLockDictionaryStorage<TKey, TValue> : ICacheStorage<TKey, TValue>
    {
        private Dictionary<TKey, TValue> m_storage;
        private readonly object m_writeLock = new object();
        public FreeLockDictionaryStorage()
        {
            m_storage = new Dictionary<TKey, TValue>();
        }

        public TValue Get(TKey key)
        {
            TValue value = default(TValue);

            if (this.m_storage.TryGetValue(key, out value))
            {
                return value;
            }
            return value;
        }

        public void Set(TKey key, TValue value)
        {
            lock (this.m_writeLock)
            {
                if (!this.m_storage.ContainsKey(key))
                {
                    var newStorage = this.m_storage.ToDictionary(
                 p => p.Key,
                 p => p.Value,
                 this.m_storage.Comparer);
                    newStorage.Add(key, value);
                    this.m_storage = newStorage;
                }
            }
        }

        public bool IsContains(TKey key)
        {
            return m_storage.ContainsKey(key);
        }


    }
}
